import React,{useState,useEffect,useRef} from 'react';
import {Button, Input, message, Modal, Space, Table} from "antd";
import Axios from "../../util/axios"
import AddTabCode from "./AddTabCode"




const { Search } = Input;
const { confirm } = Modal;
function TabCode(props) {
    const [dataSource,setdataSource] =useState([]);
    const columns = [
        {
            title: '序号',
            dataIndex: 'stoneId',
            key: 'stoneId',
        },
        {
            title: '商品编码',
            dataIndex: 'commodityCode',
            key: 'commodityCode',

        },
        {
            title: '商品名称',
            dataIndex: 'commodityName',
            key: 'commodityName'
        },
        {
            title: '模具号',
            dataIndex: 'dieNo',
            key: 'dieNo'
        },

        {
            title: '供应商',
            dataIndex: 'supplier',
            key: 'supplier'
        },

        {
            title: '款号',
            dataIndex: 'itemNumber',
            key: 'itemNumber'
        },
        {
            title: '标签单价',
            dataIndex: 'tagUnitPrice',
            key: 'tagUnitPrice'
        },

        {
            title: '销售工费',
            dataIndex: 'salesLaborCost',
            key: 'salesLaborCost'
        },

        {
            title: '工费计价',
            dataIndex: 'laborCosPricing',
            key: 'laborCosPricing'
        },

        {
            title: '操作',
            align:'center',
            render: (item)=>{
                return(
                    <Space>
                        <Button size="small" type="primary"
                                onClick={()=>{editMethod(item)}}>编辑</Button>
                        <Button  size="small" type="danger"
                                 onClick={()=>{confirmMethod(item)}}>删除</Button>
                    </Space>
                )
            }
        }
    ];
    //页面显示
    useEffect(() =>{
        displayTable();
    },[]);
    const displayTable =() => {
        Axios.get("/productCodeSet").then((res) => {
            setdataSource(res.data.data)
        })
    }
    //添加
    const [isAddvisible,setisAddvisible] =useState(false);
    const addTabFrom =useRef(null);
    const addFormOk =() =>{
        console.log(addTabFrom);
        addTabFrom.current.validateFields().then(value => {
            setisAddvisible(false);
            //添加后重置
            addTabFrom.current.resetFields();
            //post到后端，生成id，再设置DataSource，方便后面删除和更新
            Axios.post("/addProductCode",{...value})
                .then(res =>{
                    console.log(res.data);
                    setdataSource([...dataSource,res.data.data])
                    displayTable();
                })
        }).catch(err =>console.log(err))
    }

    //删除
    const confirmMethod =(item) =>{
        confirm({
            title: '你想要删除吗?',
            content: '确定要删除这条数据吗?',
            onOk() {
                deleteMethod(item);
                message.success('已成功删除');
            },
            onCancel() {
                message.error('删除失败');
            },
        });
    }
    const deleteMethod =(item) =>{
        Axios.get("/deleteProductCode", {params:{stoneId:item.stoneId
            }}).then((res) =>{
            setdataSource([...dataSource,res.data.data])
            displayTable();
        }).catch(err =>console.log(err))
    }

    //查询
    const onSearch = (value) => {
        Axios.post("/searchProductCode", {neirong:value}).then((res) =>{
            console.log(res);
            if (res){
                let arr = res.data.data.map((item,key) =>{
                    return {
                        key:key,
                        stoneId:item.stoneId,
                        commodityCode:item.commodityCode,
                        commodityName:item.commodityName,
                        dieNo:item.dieNo,
                        supplier:item.supplier,
                        itemNumber:item.itemNumber,
                        tagUnitPrice:item.tagUnitPrice,
                        salesLaborCost:item.salesLaborCost,
                        laborCosPricing:item.laborCosPricing
                    }
                })
                setdataSource(arr)
            }
        }).catch(err =>console.log(err))
    }

    //修改
    const [current,setcurrent] =useState(null);
    const editMethod =(item)=>{
        //同步，不然刷新后就没了
        setTimeout(() =>{
            setisupdatevisible(true);
            updateForm.current.setFieldsValue(item)
        },0)
        setcurrent(item)
    }
    const [isupdatevisible,setisupdatevisible] =useState(false);
    const updateForm =useRef(null);
    const updateFormOk =() =>{
        updateForm.current.validateFields().then(value => {
            setisupdatevisible(false);
            setdataSource(dataSource.map((item) =>{
                if (item.stoneId===current.stoneId){
                    return {
                        ...item,
                        ...value
                    }
                }
                return item

            }))
            //把更改的向后台发送过去，否则刷新页面之后没了
            Axios.post("/updateProductCode",{value})
        })
    }
    //批量删除
    const [idArr] =useState([])
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
           idArr.push(selectedRowKeys)
        }
    }
    const batchDelete =(item) =>{
        confirm({
            title: '你想要批量删除所选中的所有数据吗?',
            content: '确定批量删除所选中的所有数据吗?',
            onOk() {
                deleteTable(item);
                // console.log(idArr)
                message.success('已成功删除');
            },
            onCancel() {
                message.error('删除失败');
            },
        });
    }
    const deleteTable=() =>{
        console.log(idArr);
        Axios.post("/deleteTableCode",{deleteId:idArr}).then((res) =>{
            console.log(idArr)
            // setdataSource([...dataSource,res.data.data])
            // displayTable();
        }).catch(err =>console.log(err))
    }


    return (
        <div>
            <div className="site-button-ghost-wrapper">
                <ul>
                    <li> <Button  type="primary" onClick={() =>
                    {setisAddvisible(true)}}>新增编码</Button></li>
                    <li> <Button type="danger" onClick={() =>{batchDelete()}}>批量删除</Button></li>
                    <li>
                        <Search placeholder="请输入关键字搜索"
                                onSearch={onSearch}
                                enterButton />
                    </li>
                </ul>
                <div className="CodeHead">产品编码表</div>
                <Table
                    rowSelection={{
                        ...rowSelection
                    }}
                    dataSource={dataSource}
                    columns={columns}
                    pagination={{pageSize:3}}
                    scroll={{y:240}}
                    rowKey="stoneId"
                />
                <Modal
                    visible={isAddvisible}
                    title="增加编码规则"
                    okText="确定"
                    cancelText="取消"
                    onCancel={() =>{
                        setisAddvisible(false)
                    }}
                    onOk={()=>addFormOk()}
                >
                    <AddTabCode ref={addTabFrom} ></AddTabCode>
                </Modal>
                <Modal
                    visible={isupdatevisible}
                    title="修改编码规则"
                    okText="确定"
                    cancelText="取消"
                    onCancel={() =>{
                        setisupdatevisible(false)
                    }}
                    onOk={()=>updateFormOk()}
                >
                    <AddTabCode ref={updateForm} ></AddTabCode>
                </Modal>
            </div>
        </div>
    );
}

export default TabCode;